<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>网页聊天</title>
    <link rel="stylesheet" href="./css/comment.css">
    <link rel="stylesheet" href="./css/client.css">

</head>

<body>
    <div class="cover"></div>
    <div class="client-container">
        <div class="main">
            <div class="left">
                <div class="user">

                </div>
                <div class="search">
                    <input type="text">
                    <button></button>
                </div>
                <div class="tab">
                    <div class="tab-session"></div>
                    <div class="tab-friend"></div>
                </div>
                <ul class="list" id="session-list">
                    <li>
                        <h3>lisi</h3>
                        <p>晚上吃啥</p>
                    </li>
                    <li class="selected">
                        <h3>lisi</h3>
                        <p>晚上吃啥</p>
                    </li>
                    <li>
                        <h3>lisi</h3>
                        <p>晚上吃啥</p>
                    </li>
                    <li>
                        <h3>lisi</h3>
                        <p>晚上吃啥</p>
                    </li>
                    <li>
                        <h3>lisi</h3>
                        <p>晚上吃啥</p>
                    </li>
                    <li>
                        <h3>lisi</h3>
                        <p>晚上吃啥</p>
                    </li>
                </ul>

                <ul class="list hide" id="friend-list">
                    <!-- <li>
                        <h4>lisi</h4>
                    </li>
                    <li>
                        <h4>lisi</h4>
                    </li>
                    <li>
                        <h4>lisi</h4>
                    </li>
                    <li>
                        <h4>lisi</h4>
                    </li>
                    <li>
                        <h4>lisi</h4>
                    </li> -->
                </ul>

            </div>
            <div class="right">
                <div class="title"></div>
                <div class="message-show">
                    <!-- <div class="message message-left">
                        <div class="box">
                            <h3>lisi</h3>
                            <p class="p-left">今天吃啥</p>
                        </div>
                    </div>
                    <div class="message message-right">
                        <div class="box">
                            <h3 class="h3-right">zhangsan</h3>
                            <p class="p-right">随便</p>
                        </div>
                    </div> -->
                </div>
                <textarea class="message-input"></textarea>
                <div class="ctrl">
                    <button>发送</button>
                </div>

            </div>
        </div>
    </div>
    <script src="./js/jquery-3.7.1.min - .js"></script>
    <script src="./js/comment.js"></script>
    <script src="./js/client.js"></script>
    <script>
        function getUserInfo() {
            $.ajax({
                type: 'get',
                url: 'http://127.0.0.1:8080/user/getUserInfo?userId=' + localStorage.getItem('id'),
                success: function (result) {
                    if (result != null && result.data != null && result.data.userId != 0) {
                        $('.user').text(result.data.userName);
                    } else {
                        alert("当前用户未登录!");
                        location.assign('login.html');
                    }
                }
            });
        }
        getUserInfo();

        // 获取好友列表
        function getFriendList() {
            $.ajax({
                type: 'get',
                url: 'http://127.0.0.1:8080/user/getFriendList?userId=' + localStorage.getItem('id'),
                success: function (result) {
                    let friendListUL = document.querySelector('#friend-list');
                    friendListUL.innerHTML = '';
                    for (let friend of result.data) {
                        let li = document.createElement('li');
                        li.innerHTML = '<h4>' + friend.friendName + '</h4>';
                        li.setAttribute('friend-id', friend.friendId);
                        friendListUL.appendChild(li);

                        // 给每个li添加点击事件
                        li.onclick = function () {
                            clickFriend(friend);
                        }
                    }
                },
                error: function () {
                    console.log('获取好友列表失败!');
                }
            });
        }
        getFriendList();

        // TODO
        function clickFriend(friend) {
            let sessionLi = findSessionByName(friend.friendName);
            let sessionListUL = document.querySelector('#session-list');

            if (sessionLi == null) {
                // 如果没有对应的会话
                sessionLi = document.createElement('li');
                sessionLi.innerHTML = '<h3>' + friend.friendName + '</h3>' + '<p></p>';
                sessionListUL.insertBefore(sessionLi, sessionListUL.children[0]);

                sessionLi.onclick = function () {
                    clickSession(sessionLi);
                }
                sessionLi.click();

                // 调用后端接口并将会话Id进行存储
                createSession(friend.friendId, sessionLi);
            } else {
                // 有对应的会话
                sessionListUL.removeChild(sessionLi)
                sessionListUL.insertBefore(sessionLi, sessionListUL.children[0]);
                sessionLi.click();
            }
            let tabSession = document.querySelector('.tab .tab-session');
            tabSession.click();
        }

        function createSession(friendId, sessionLi) {
            $.ajax({
                type: 'post',
                url: 'session/addSession',
                data: {
                    toUserId: friendId,
                    userId: localStorage.getItem('id'),
                },
                success: function (result) {
                    console.log(result);
                    console.log("会话创建成功! sessionId = " + result.data);
                    sessionLi.setAttribute('message-session-id', result.data);
                },
                error: function () {
                    console.log('会话创建失败!');
                }
            });
        }

        function findSessionByName(friendName) {
            let sessionLis = document.querySelectorAll("#session-list>li");
            for (let sessionLi of sessionLis) {
                let h3 = sessionLi.querySelector('h3')
                if (h3.innerHTML == friendName) {
                    return sessionLi;
                }
            }
            return null;
        }

        function getSessionList() {
            $.ajax({
                type: 'get',
                url: '/session/getSessionList?userId=' + localStorage.getItem('id'),
                success: function (result) {
                    let sessionList = document.querySelector('#session-list');
                    sessionList.innerHTML = '';

                    console.log(result.data);
                    for (let session of result.data) {
                        let li = document.createElement('li');
                        li.setAttribute('message-session-id', session.sessionId);

                        li.innerHTML = '<h3>' + session.friends[0].friendName + '</h3>'
                            + '<p>' + session.lastMessage + '</p>';
                        sessionList.appendChild(li);

                        li.onclick = function () {
                            clickSession(li);
                        }
                    }

                }
            })
        }
        getSessionList();

        function clickSession(currentLi) {
            // 使被点击的li变亮
            let allLis = document.querySelectorAll('#session-list>li');
            activeSession(allLis, currentLi);

            // 获取对话
            let sessionId = currentLi.getAttribute("message-session-id");
            getHistoryMessage(sessionId);
        }

        function activeSession(allLis, currentLi) {
            for (let li of allLis) {
                if (li == currentLi) {
                    li.className = 'selected';
                } else {
                    li.className = ''
                }
            }
        }

        function getHistoryMessage(sessionId) {
            // 将标题和内容先进行清空
            let titleDiv = document.querySelector('.right .title');
            titleDiv.innerHTML = '';
            let messageShowDiv = document.querySelector('.right .message-show');
            messageShowDiv.innerHTML = '';

            // 将被点击的会话名称填写到对话框上方
            let selectedH3 = document.querySelector('#session-list .selected>h3');
            if (selectedH3) {
                titleDiv.innerHTML = selectedH3.innerHTML;
            }

            // 获取所有的消息
            $.ajax({
                type: 'get',
                url: '/message/getMessagesBySessionId?sessionId=' + sessionId,
                success: function (result) {
                    for (let message of result.data) {
                        addMessage(messageShowDiv, message);
                    }
                    scrollBottom(messageShowDiv);
                }
            });
        }

        function addMessage(messageShowDiv, message) {
            let userId = localStorage.getItem('id');
            let messageDiv = document.createElement('div');

            if (userId == message.fromId) {
                // 自己发送的消息
                messageDiv.className = 'message message-right';
                messageDiv.innerHTML = '<div class="box">'
                    + '<h3 class="h3-right">' + message.fromName + '</h3>'
                    + '<p class="p-right">' + message.content + '</p>'
                    + '</div>';
            } else {
                // 别人发送的消息
                messageDiv.className = 'message message-left';
                messageDiv.innerHTML = '<div class="box">'
                    + '<h3>' + message.fromName + '</h3>'
                    + '<p class="p-left">' + message.content + '</p>'
                    + '</div>';
            }

            messageShowDiv.appendChild(messageDiv);
        }

        function scrollBottom(elem) {
            let clientHeight = elem.offsetHeight;
            let scrollHeight = elem.scrollHeight;
            elem.scrollTo(0, scrollHeight - clientHeight);
        }


        // webSocket的初始化设置
        let userId = localStorage.getItem('id');
        // 当访问网址的时候就会建立连接
        let webSocket = new WebSocket(`ws://127.0.0.1:8080/webSocket?userId=${userId}`);
        webSocket.onopen = function () {
            console.log("onopen");
        }
        webSocket.onmessage = function (element) {
            let response = JSON.parse(element.data);
            console.log(response);
            if (response.type == 'message') {
                // 处理消息响应
                handleMessage(response);
            } else {
                // response 的 type 出错!
                console.log("response.type 不符合要求!");
            }
        }

        webSocket.onerror = function () {
            console.log('onerror');
        }
        webSocket.onclose = function () {
            console.log('onclose');
        }

        function handleMessage(response) {
            // 1.左边消息栏
            let curSessionLi = findSessionLi(response.sessionId);
            if (curSessionLi == null) {
                curSessionLi = document.createElement('li');
                curSessionLi.setAttribute('message-session-id', response.sessionId);
                curSessionLi.innerHTML = '<h3>' + response.fromName + '</h3>'
                    + '<p></p>';

                // 点击事件的处理
                curSessionLi.onclick = function () {
                    clickSession(curSessionLi);
                }
            }

            let p = curSessionLi.querySelector('p');
            if (response.content.length > 10) {
                response.content = response.content.substring(0, 10) + '...';
            }
            p.innerHTML = response.content;

            // 放到列表最上方
            let sessionListUL = document.querySelector('#session-list');
            sessionListUL.insertBefore(curSessionLi, sessionListUL.children[0]);

            // 2.右边消息框
            if (curSessionLi.className == 'selected') {
                // 把消息列表添加一个新消息. 
                let messageShowDiv = document.querySelector('.right .message-show');
                addMessage(messageShowDiv, response);
                scrollBottom(messageShowDiv);
            }
        }

        function findSessionLi(sessionId) {
            let sessionLis = document.querySelectorAll('#session-list li');
            for (let li of sessionLis) {
                let temp = li.getAttribute("message-session-id")
                if (temp == sessionId) {
                    return li;
                }
            }
            return null;
        }

        // 给发送按钮进行设置
        function initSendButton() {
            let sendButton = document.querySelector('.right .ctrl button');
            let messageInput = document.querySelector('.right .message-input');

            sendButton.onclick = function () {
                if (!messageInput.value) {
                    return;
                }

                let selectedLi = document.querySelector('#session-list .selected');
                if (selectedLi == null) {
                    // 当前没有 li 标签被选中. 
                    return;
                }
                let sessionId = selectedLi.getAttribute('message-session-id');

                let req = JSON.stringify({
                    type: 'message',
                    sessionId: sessionId,
                    content: messageInput.value
                })

                webSocket.send(req);
                messageInput.value = '';
            }
        }
        initSendButton();
    </script>
</body>

</html>